package com.jufa_3.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jufa_3.common.R;
import com.jufa_3.common.WeiChat;
import com.jufa_3.dto.Login;
import com.jufa_3.entity.ComboOrder;
import com.jufa_3.entity.LoginInfo;
import com.jufa_3.entity.User;
import com.jufa_3.mapper.UserMapper;
import com.jufa_3.service.ComboOrderService;
import com.jufa_3.service.LoginInfoService;
import com.jufa_3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginInfoService loginInfoService;

    @Autowired
    private ComboOrderService comboOrderService;

    @Autowired
    private UserService userService;

    @Override
    public R<Object> byVerifyCodeCheckRegister(Login login) {
        //从Redis中获取缓存的验证码
        Object saveCode = redisTemplate.opsForValue().get(login.getPhoneNum());
        String verifyCode = login.getVerifyCode();
        //验证码对比
        if (saveCode != null && saveCode.equals(verifyCode)) {   //验证手机号成功
            User user = userService.lambdaQuery().eq(User::getOpenId, login.getOpenId()).one();
            if (user != null) {
                String ipAddress = login.getIP();
                // IP 城市
                // login.setCity();
                LocalDateTime now = LocalDateTime.now();
                // 增设登陆记录
                loginInfoService.save(new LoginInfo(login.getOpenId(), now, ipAddress, "未启用"));
                return R.success(user);
            } else {
                // 未查询到，放过去注册
                user = addUserAndRecord(login);
            }
            // 移除验证码
            redisTemplate.delete(login.getPhoneNum());
            return R.success(user);
        } else {
             return R.error(4002, "验证码失效或输入错误！");
        }
    }

    @Override
    @Transactional
    public User addUserAndRecord(Login login) {
        // 设置新用户信息
        User user = userService.lambdaQuery().eq(User::getOpenId, login.getOpenId()).one();
        LocalDateTime now = LocalDateTime.now();
        if (user == null) {
            String loginType = login.getVerifyCode() != null ? "2" : "1";
            String phoneNum = login.getVerifyCode() != null ? login.getPhoneNum() : WeiChat.getUserPhoneNum(login.getPhoneCode());
            // 新用户信息入库
            user = new User(login.getOpenId(), loginType, phoneNum, now, now, login.getSource());
            this.save(user);
            Object nup = redisTemplate.opsForValue().get("newUserPrice");
            Object pup = redisTemplate.opsForValue().get("pullUserPrice");
            comboOrderService.save(new ComboOrder(
                    login.getOpenId(),
                    "体验版套餐",
                    now,
                    Float.parseFloat(nup.toString()),
                    Float.parseFloat(nup.toString()),
                    now.plusYears(1),
                    "newUser"));
            // 拉新用户要为来源用户充值金额(其他来源分不充：0: 未知来源 1---6 扫描不同二维码 )
            if (login.getSource().length() > 2) {
                comboOrderService.save(new ComboOrder(
                        login.getSource(),
                        "体验版套餐",
                        now,
                        Float.parseFloat(pup.toString()),
                        Float.parseFloat(pup.toString()),
                        now.plusYears(1),
                        "pullUser"));
            }
        }
        // 记录此条登陆信息
        loginInfoService.save(new LoginInfo(login.getOpenId(), now, login.getIP(), "未启用"));
        return user;
    }

}
